
from concurrent.futures import ThreadPoolExecutor, as_completed
import json
from fastapi import APIRouter, Depends, Request
import numpy as np
from xtquant import xtdata

from analyse.kline_handler.rise_and_fall_handler import RiseAndFallHandler
from analyse.trend_handler import Trend
from api.kline import KlineRequest, fetch_and_save_kline, get_db
from bs.kline import full_update_kline
from router import return_json
from utils.kline import get_range_volume_mean
from utils.stock import get_stock_list

router = APIRouter()



@router.get("/get/{code}")
def get_kline(code: str):
    klines=xtdata.get_market_data_ex(field_list=[],stock_list=[code],period="1d",count=-1,dividend_type='front_ratio', fill_data=False)
    return return_json(klines[code].to_dict(orient='records'))

@router.post("/trend/get/{code}")
async def get_kline(code: str,request: Request):
    body = await request.json() 
    
    ticks=xtdata.get_market_data_ex(field_list=[],stock_list=[code],period="1d",count=-1,dividend_type='front', fill_data=False)
    klines=ticks[code].to_dict(orient='records')
    length = int(body.get("length", len(klines))) 
   
    trend=Trend({'klines': klines[0:length]})
    trend.iterate()


    return return_json({
        "trends": trend.trends,
        "klines": trend.original_klines,
    })



def update_full_kline():
    
    # full_update_kline()
    stock_list=get_stock_list()
    stock_list = sorted(stock_list)
    filtered_stock_list = [code for code in stock_list if code > "836717.BJ"]
    # print(len(filtered_stock_list))
    # for code in stock_list:
    #     full_update_kline()
     # 使用多线程执行
    max_workers = 10  # 设置线程池大小
    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        # 提交任务到线程池
        future_to_code = {
            executor.submit(fetch_and_save_kline, KlineRequest(code=code)): code 
            for code in filtered_stock_list
        }
        
        # 处理完成的任务
        for future in as_completed(future_to_code):
            code = future_to_code[future]
            try:
                result = future.result()
                print(f"完成处理 {code}: {result}")
            except Exception as exc:
                print(f"{code} 处理失败: {exc}")
       

